﻿using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Pasta.Medio.Concrete;
using Pasta.Medio.Configuration;
using Pasta.Medio.Dialogs;
using Pasta.Medio.Domain;
using Pasta.Medio.Models;
using Pasta.Medio.Properties;

namespace Pasta.Medio.Controls
{
	public partial class ScanTab : TabBase
	{
		private string _location;
		private AppSettings Settings = Program.Settings;
		private SortableBindingList<Recording> Catalog = Program.Catalog;
		private SortableBindingList<MediaView> _media = new SortableBindingList<MediaView>();

		public ScanTab()
		{
			InitializeComponent();
			Settings = Program.Settings;
		}

		public override void RefreshPage()
		{
			base.RefreshPage();
		}

		private void DashboardTab_Load(object sender, EventArgs e)
		{
			InitScanGrid();
		}

		private void InitScanGrid()
		{
			scanGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
			mRecordedOn.DefaultCellStyle.Format = Settings.RenamePattern;
			mName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
			mCamera.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
			mSha1.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
			scanGrid.AutoGenerateColumns = false;
			//! VIRTUAL MODE
			//mediaGrid.VirtualMode = true;
			//mediaGrid.CellValueNeeded += mediaGrid_CellValueNeeded;

			catalogGrid.DataSource = Catalog;
		}

		private void Scan()
		{
			folderBrowser.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
			if (folderBrowser.ShowDialog() == DialogResult.OK)
			{
				Scan(folderBrowser.SelectedPath);
			}
		}

		public void Scan(string path)
		{
			ScannerForm sf = new ScannerForm(path);
			if (sf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				try
				{
					UseWaitCursor = true;
					Application.DoEvents();
					_media = sf.Media;
					scanGrid.DataSource = _media;
					//
					ShowScanReport();
					var cameras = _media.Where(m => !String.IsNullOrEmpty(m.Camera)).Select(m => m.Camera).Distinct().ToDictionary(m => m, m => m.GetHashCode());
				}
				finally
				{
					UseWaitCursor = false;
				}
			}
		}

		private void ShowScanReport()
		{
			var imageTypes = from m in _media.Where(r => r.Type == Enums.Type.Image)
							 group m by Path.GetExtension(m.Name).Substring(1) into grp
							 select new { Type = grp.Key, Count = grp.Count() };
			mediaImageChart.Series["Types"].Points.DataBind(imageTypes, "Type", "Count", null);

			var videoTypes = from m in _media.Where(r => r.Type == Enums.Type.Video)
							 group m by Path.GetExtension(m.Name).Substring(1) into grp
							 select new { Type = grp.Key, Count = grp.Count() };
			mediaVideoChart.Series["Types"].Points.DataBind(videoTypes, "Type", "Count", null);
		}

		void scanGrid_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
		{
			var mv = _media[e.RowIndex];
			string col = scanGrid.Columns[e.ColumnIndex].DataPropertyName;
			if (col == "DisplayId")
				e.Value = mv.DisplayId;
			//else if (col == "InCatalog" ) //&& mv.InCatalog)
			//	e.Value = Properties.Resources.New_24;
			else if (col == "Name")
				e.Value = mv.Name;
			else if (col == "Rename")
				e.Value = mv.TargetName;
			else if (col == "Type")
				e.Value = mv.Type;
			else if (col == "Camera")
				e.Value = mv.Camera;
			else if (col == "RecordedOn" && mv.RecordedOn.HasValue)
				e.Value = mv.RecordedOn.Value;
			else if (col == "Size")
				e.Value = mv.Size;
			else if (col == "Sha1")
				e.Value = mv.Sha1;
		}


		private void catalogGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
		{
			var rec = Catalog[e.RowIndex];
			var row = catalogGrid.Rows[e.RowIndex];
			string col = catalogGrid.Columns[e.ColumnIndex].DataPropertyName;
			object val = row.Cells[e.ColumnIndex].Value;

			if (col == "TypeEnum")
			{
				e.Value = (int)val == (int)Enums.Type.Image ? Resources.Picture_16 : Resources.Movie_16;
			}
			else if (col.EndsWith("Enum"))
			{
				e.Value = Program.Enums.GetName((int?)val);
			}
		}


		private void cbShowSha1_CheckedChanged(object sender, EventArgs e)
		{
			catalogGrid.Columns["rSha1"].Visible = cbShowSha1.Checked;
		}

		private void scanGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
		{
			var mv = _media[e.RowIndex];
			var row = scanGrid.Rows[e.RowIndex];
			string col = scanGrid.Columns[e.ColumnIndex].DataPropertyName;
			object val = row.Cells[e.ColumnIndex].Value;
			if (col == "InCatalog")
			{
				e.Value = mv.InCatalog ? Properties.Resources.New_16 : Properties.Resources.Ok_16;
			}
			else if (col == "Type")
			{
				e.Value = mv.Type == Enums.Type.Image ? Resources.Picture_16 : Resources.Movie_16;
			}
		}

		private void scanGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
		{
			try
			{
				var mv = _media[e.RowIndex];
				Recording rec = new Recording();
				rec.Name = mv.TargetName;
				rec.TypeEnum = (int)mv.Type;
				rec.CameraEnum = 0;
				rec.RecordedOn = mv.RecordedOn;
				rec.CatalogedOn = DateTime.Now;
				rec.Size = mv.Size;
				rec.Sha1 = mv.Sha1;
				using (var db = new MedioEntities())
				{
					db.AddObject("Recordings", rec);
					db.SaveChanges();
				}
				//Program.Repository.Add(rec);
				//Program.Context.SaveChanges();
			}
			catch (Exception ex)
			{
				MessageBox.Show("Error: " + ex.Message);
			}
		}

		private void btnBrowse_Click(object sender, EventArgs e)
		{
			Scan(_location);
		}

		private void lblLocation_Click(object sender, EventArgs e)
		{
			if (folderBrowser.ShowDialog() == DialogResult.OK)
			{
				_location = folderBrowser.SelectedPath;
				lblLocation.Text = _location;
			}
		}

		private void lblLocation_TextChanged(object sender, EventArgs e)
		{
			btnBrowse.Enabled = Directory.Exists(_location);
		}

	}
}
